/*
 * Copyright (c) 2021 Shenzhen Kaihong Digital Industry Development Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import router from '@system.router'
import dd from '@ohos.data.distributedData';

export default {
    data: {
        title: "",
        result: "",
        mineimage: "",
        otherimage: "",
        displayimg: false,
    },
    kv: {},
    kvm: {},
    onInit() {
//        this.title = this.$t('strings.world');
        this.onopen();
    },

    onBack: function () {
        router.replace({
            uri: "pages/index/index"
        })
    },

    onopen: function(){
        this.kv = null;
        let that = this;

        try {
            const kvManagerConfig = {
                bundleName : 'com.view.datashareddemo',
                userInfo : {
                    userId : '0',
                    userType : 0
                }
            }
            dd.createKVManager(kvManagerConfig).then((manager) => {
                console.log("dkvstore createKVManager success");
                that.kvm = manager;
                that.getStore()
            }).catch((err) => {
                console.log("dkvstore createKVManager err: "  + JSON.stringify(err));
            });
        } catch (e) {
            console.log("dkvstore An unexpected error occurred. Error:" + e);
        }
    },
    getStore: function(){
        try {
            const options = {
                createIfMissing : true,
                encrypt : false,
                backup : false,
                autoSync : true,
                kvStoreType : 1,
                securityLevel : 3,
            };
            let that = this;
            this.kvm.getKVStore('testcoap', options).then((store) => {
                console.log("dvkstore getKVStore success");
                that.kv = store;
                store.on('dataChange', 1, function (data) {
                    // {"deviceId":"","insertEntries":[],"updateEntries":[{"key":"time","value":{"type":5,"value":6199703}}],"deleteEntries":[]}
                    // {"deviceId":"","insertEntries":[],"updateEntries":[{"key":"result","value":{"type":0,"value":"shitou"}}],"deleteEntries":[]}
                    console.log("dvkstore dataChange callback call data: " + JSON.stringify(data));

                    let result = data.updateEntries[0].value.value;
                    //false代表不显示对方出的结果

                    if ("request" == result) {
                        //对方发来请求对战
                        that.title = "对方请求对战，请点击应答对战按钮"
                        that.displayimg = false;
                        that.otherimage = "";
                        that.mineimage = "";
                        console.log("dvkstore datachange request");
                    } else if ("response" == result) {
                        //对方发来应答对战
                        that.title = "对方应答对战，可以点击按钮出石头剪刀布";
                        that.displayimg = false;
                        that.otherimage = "";
                        that.mineimage = "";
                        console.log("dvkstore datachange response");
                    } else if (result == "shitou") {
                        //对方出石头
                        if ("" == that.mineimage) {
                            that.title = "对方已出，请尽快出拳";
                        } else {
                            //我方已经出过
                            that.title = "对方已出，我方已出，显示结果";
                        }

                        that.otherimage = "common/images/shitou.png"
                        console.log("dvkstore datachange shitou");
                    } else if ("jiandao" == result) {
                        //对方出剪刀
                        if ("" == that.mineimage) {
                            that.title = "对方已出，请尽快出拳";
                        } else {
                            //我方已经出过
                            that.title = "对方已出，我方已出，显示结果";
                        }
                        that.otherimage = "common/images/jiandao.png"
                        console.log("dvkstore datachange jiandao");
                    } else if ("bu" == result) {
                        //对方出布
                        if ("" == that.mineimage) {
                            that.title = "对方已出，请尽快出拳";
                        } else {
                            //我方已经出过
                            that.title = "对方已出，我方已出，显示结果";
                        }
                        that.otherimage = "common/images/bu.png"
                        console.log("dvkstore datachange bu");
                    }
                    if (that.otherimage != "" && that.mineimage != "") {
                        //otherimage和mineimage均有结果时，显示对方的结果
                        that.displayimg = true;
                        console.log("dvkstore displayimg = true");
                    }
                });
                store.on('syncComplete', function (data) {
                    console.log("dvkstore syncComplete callback call data: " + data);
                });
            }).catch((err) => {
                console.log("dvkstore getKVStore err: "  + JSON.stringify(err));
            });
        } catch (e) {
            console.log("dvkstore An unexpected error occurred. Error:" + e);
        }
    },
    onclose: function(){
        if(this.kv == null){
//            this.data.title = 'open first';
            return;
        }
        this.kv = null;
        this.title = 'closed';
    },
    onput: function(){
        console.log("dvkstore onput");
//                this.title = 'begin to put.\n'
        if(this.kv == null){
            console.log("dvkstore onput kv == null");
            this.title = 'open first';
            return;
        }
        let that = this;
        this.kv.put('time', new Date().getTime()).then(()=>{
//            that.title += 'put ok';
        }).catch((err)=>{
            console.log("dvkstore onput catch error");
            console.log(err)
//            this.title = 'put err: '+JSON.stringify(err);
        })
    },
    onget: function(){
        console.log("dvkstore onget");
        if(this.kv == null){
            console.log("dvkstore onget kv == null");
//            this.title = 'open first';
            return;
        }

        let that = this;
        this.kv.get('time').then((data)=>{
            console.log('dvkstore get')
            console.log("dvkstore" + data)
            that.title = 'get ok: ' + JSON.stringify(data);
        }).catch((err)=>{
            console.log("dvkstore onget catch error");
            console.log(err)
        })
    },
    shitou: function(){
        this.title = "我方出石头";
        this.result = "shitou";
        this.putmethod(this.result);
    },
    jiandao: function(){
        this.title = "我方出剪刀";
        this.result = "jiandao";
        this.putmethod(this.result);
    },
    bu: function() {
        this.title = "我方出布";
        this.result = "bu";
        this.putmethod(this.result);
    },
    request: function(){
        //申请对战
        this.title = "我方申请对战";
        this.result = "request";
        this.displayimg = false;
        this.otherimage = "";
        this.mineimage = "";
        this.putmethod(this.result);
    },
    response: function() {
        //应答对战
        this.title = "我方应答对战";
        this.displayimg = false;
        this.otherimage = "";
        this.mineimage = "";
        this.result = "response";
        this.putmethod(this.result);
    },
    end: function(){
        this.onclose();
    },

    putmethod: function(str){
        if(this.kv == null){
            console.log("dvkstore putmethod kv == null");
            return;
        }
        let that = this;
        this.kv.put('result', str).then(()=>{
            if ("shitou" == str || "jiandao" == str || "bu" == str) {
                console.log("dvkstore putmethod ok");
                that.mineimage = "common/images/" + str + ".png";

            }
            if (that.otherimage != "" && that.mineimage != "") {
                //otherimage和mineimage均有结果时，显示对方的结果
                that.displayimg = true;
                console.log("dvkstore displayimg = true");
            }

        }).catch((err)=>{
            console.log("dvkstore putmethod catch error");
            console.log(err);
        })


    }
}



